from DataTools import DataGeterMain
from DataGeter import aksharePack, tusharePack
import datetime
import sys
import os


#%%----------------------------------------------------------------
# 股票信息 代码等模块
def getCodeAndDetail(
    MainPath=r"D:/StockDatas/", subPath=r"basic/", keylist=["ts_code", "list_date"]
):
    """
    载入之前文件 获取keylist 中标注的信息
    ```python
    keylist=["ts_code",         # eg. 000001.SZ
            'name',             # eg. 平安银行
            "area"              # eg. 深圳
            "industry"          # eg. 行业
            "enname"            # eg. Ping An Bank Co., Ltd.
            "market"            # eg. 主板/中小板/创业板/科创板
            "is_hs"             # eg. 是否沪深港通标的，N否 H沪股通 S深股通
            "exchange"          # eg.SZSE/SSE 类似ts_code后面的.SZ|.SH
            "total_divident":   "累计股息(%)" 总的分红数量(如果AK模块没失效,可以正常获取)
            "divident_pre_year":"年均股息(%)" # 每年分红的数量(如果AK模块没有失效,可以正常获取)
            "divident_times":   "分红次数" float
            "total_funding":    "融资总额(亿)" float
            "funding_times":    "融资次数"  float
            "list_date":        # eg. 上市时间 2020-10-10
     ]
    if type(keylist) = list:
         retrun dic # 所筛选的信息
    else:
        df #(全部信息)
    ```
    ['2006-10-27', '工商银行', 0]  ['2006-10-27',  0] area永远在最后

    """
    df = DataGeterMain.GetStockList(MainPath=MainPath, subPath=subPath).run()
    if isinstance(keylist, list):
        df = df.loc[:, keylist]
        if "ts_code" in keylist:
            df[["code", "area_boll"]] = df["ts_code"].str.split(".", expand=True)
            df["area_boll"] = df["area_boll"].apply(
                lambda x: 1 if x == "SZ" else (0 if "SH" else None)
            )
        else:
            print("输入信息有误,datatool --> 26")
            return None
        df = df.set_index("code")
        df = df.drop("ts_code", axis=1)
        dic = df.T.to_dict("list")
        return dic
    else:
        return df


def getTradedayinfo(MainPath=r"D:/StockDatas/", subPath=r"basic/", mode="all"):
    """
    + path=r"D:/StockDatas/"
    + mode='all' ret df
        + daylist ret alldaylist
        + daylist ret openday only
        + "LastOpenDay" 最近一个交易日
    """
    con = DataGeterMain.GetTradeDays(MainPath=MainPath, subPath=subPath).run()
    if mode == "all":
        return con
    elif mode == "daylist":
        con = con.cal_date.tolist()
    elif mode == "openday":
        con = con[con.is_open == 1].cal_date.tolist()
    elif mode == "LastOpenDay":
        endday = int("".join(str(datetime.datetime.today()).split(" ")[0].split("-")))
        ind = con[con["cal_date"] == endday].index.values[0]
        con = con.loc[ind - 30 : ind]
        con = con[con.is_open == 1].cal_date.tolist()
        con.sort()
        con = str(con[-1])  # 列表已经转换为单个值
        con = con[:4] + "-" + con[4:6] + "-" + con[6:]  # 组合成标准日期
        # print(endday)
    return con


def getTicker(timmer, code):
    """
    import time
    code = "600010"
    timmer = time.localtime().tm_min
    """
    realtime = tusharePack.todays_ticks(code)
    if realtime.shape[0] < 1:
        realtime = DataGeterMain.RealTimeticker(timmer, code).run()
    return realtime


def getBar(code, feq="1min", start=None, end=None):
    """
    + code = str
    + start 到 end = 交易日日期 "19000101"
    + feq = [D:日线， 调用AK 新浪接口,返回 date, close, high, low, volume, outstanding_share(流通股), tutnove换手率
     W:周线， M:月线， 5:5分钟， 15:15分钟， 30， 60]
      注:
      如果使用None模式字都返回最近的600条数据,可能需要循环请求,注意期间间隔
    """
    if feq == "1min":
        print("ak mins ==> start")
        df = aksharePack.akmins(code)

    elif feq == "D":
        print("ts bar data ==> start, from {} to {}".format(start, end))
        df = tusharePack.get_k_data(code, start=start, end=end, ktype=feq)
        if df.shape[0] < 1:
            print("ak_bar data ==> start from {},to {}".format(start, end))
            df = aksharePack.ak_daily(code, start, end)
    else:
        print("ts_bar data ==> start {}".format(feq))
        df = tusharePack.get_k_data(code, start=start, end=end, ktype=feq)
    return df


if __name__ == "__main__":
    dic = getCodeAndDetail(path=r"D:/StockDatas/", keylist=["ts_code"])
    print(dic)
    # dic = getCodeAndDetail(
    #     path=r"D:/StockDatas/",
    #     keylist="",
    # )
    # print(dic)

    # df = getAllStockinfo(path=r"D:/StockDatas/")
    # print(df.info())
    pass